package com.lagou.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lagou.dao.StudentService;
import com.lagou.dao.impl.StudentServiceImpl;
import com.lagou.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

public class StudentServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 操作类型
         * 为空或者list:展示列表，为空时，代表从登录界面转发过来
         * add:新增
         */
        String operType = req.getParameter("operType");

        System.out.println("StudentServlet----operType---->"+operType);
        StudentService studentService = new StudentServiceImpl();

        //客户新增，新增成功后，继续跳转到客户信息列表
      if("add".equals(operType)){

          String stuJson = req.getParameter("student");
          ObjectMapper om = new ObjectMapper();
          Map stuMap = om.readValue(stuJson, Map.class);
          System.out.println("student--->"+stuMap.toString());
          int count = studentService.addStudent(stuMap);
          if (count >0 ) {
              System.out.println("新增成功。。。。。。");
          }else{
              System.out.println("新增失败！！！！！");
          }
      }

        List<Student> studentList = studentService.getStudentList();
        ObjectMapper om = new ObjectMapper();
        String studentListJson = om.writeValueAsString(studentList);
        req.setAttribute("studentList",studentListJson);
        PrintWriter writer = resp.getWriter();
        writer.append(studentListJson.toString());
        req.getRequestDispatcher("/form.html").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
